package com.jservice.api.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.jfinal.ext.kit.DateKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jservice.api.dto.RequestHeader;
import com.jservice.api.dto.Response;
import com.jservice.api.dto.ResponseHeader;
import com.jservice.framework.utils.DateUtils;
import com.jservice.framework.utils.StringUtils;
import com.wondersgroup.upp.api.core.UPPlatformRequest;
import org.springframework.beans.factory.annotation.Value;

import java.util.*;

public class BaseService {

	protected static final String METHOD_BOTH = "BOTH";
	protected static final String METHOD_POST = "POST";
	protected static final String METHOD_GET = "GET";

	@Value("${wangda.url}")
	public String ServerURL;
	@Value("${wangda.app_id}")
	public String appId;
	@Value("${wangda.private_key}")
	public String privateKey;
	@Value("${wangda.public_key}")
	public String publicKey;

	/**
	 * 参数转为String
	 * @param param
	 * @return
	 */
	public String paramsStringFilter(Object param) {
		String result = param != null ? param.toString() : "";
		result = result.trim();
		return result;
	}

	/**
	 * 参数转为Boolean
	 * @param param
	 * @return
	 */
	public boolean paramsBooleanFilter(Object param) {
		return Boolean.parseBoolean(String.valueOf(param));
	}

	/**
	 * 参数转化为Double
	 * @param param
	 * @return
	 */
	public Double paramsDoubleFilter(Object param) {
		if(param == null) {
			return null;
		}
		return Double.parseDouble(String.valueOf(param));
	}

	/**
	 * 参数转化为Integer
	 * @param param
	 * @return
	 */
	public Integer paramsIntegerFilter(Object param) {
		if(param == null) {
			return null;
		}
		return Integer.parseInt(String.valueOf(param));
	}

	/**
	 * 参数转化为Long
	 * @param param
	 * @return
	 */
	public Long paramsLongFilter(Object param) {
		if(param == null) {
			return null;
		}
		return Long.parseLong(String.valueOf(param));
	}

	/**
	 * 参数转化为Date
	 * @param param
	 * @return
	 */
	public Date paramsDateFilter(Object param) {
		if(param == null){
			return null;
		}
		Date result = param == null ? new Date() : DateKit.toDate(param.toString());
		return result;
	}

	/**
	 * 参数转化为Map
	 * @param param
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public Map paramsMapFilter(Object param) {
		Map map = new HashMap();
		if(param == null) {
			return Maps.newHashMap();
		}
		if(param.toString().length() <= 2) {
			return Maps.newHashMap();
		}
		String mspStr = param.toString().substring(1, param.toString().length() - 1);
		StringTokenizer items = null;
		for(StringTokenizer entrys = new StringTokenizer(mspStr, ",");entrys.hasMoreTokens();
		map.put(items.nextToken().trim(), items.hasMoreTokens() ? ((Object) (items.nextToken())) : null))
			items = new StringTokenizer(entrys.nextToken(), ":");
		return map;

	}

	/**
	 * 参数转为JSONObject
	 * @param param
	 * @return
	 */
	public JSONObject paramsJSONObjectFilter(Object param) {
		if(param == null) {
			return new JSONObject();
		}
		JSONObject object = new JSONObject();
		try{
			object = JSONObject.parseObject(param.toString());
		}catch (Exception e) {
			return new JSONObject();
		}
		return object;
	}


	/**
	 * 获取数量
	 * 注意：sql中必须as num
	 * @param sql
	 * @param paras
	 * @return
	 */
	public int getCount(String sql, Object ...paras) {
		Record record = Db.findFirst(sql, paras);
		return paramsIntegerFilter(record.getColumns().get("num"));
	}


	/**
	 * 把11,22,33...转成数组['11','22','33'...]
	 * @param ids
	 * @return
	 * 描述：把字符串分割成数组返回，并验证分割后的数据
	 */
	public String[] splitByComma(String ids){
		if(null == ids || ids.trim().isEmpty()){
			return null;
		}

		String[] idsArr = ids.split(",");

		for (String id : idsArr) {
			if(!StringUtils.regExpVali(id, StringUtils.regExp_integer_5)){ // 匹配字符串，由数字、大小写字母、下划线组成
				throw new RuntimeException("字符安全验证失败：" + id);
			}
		}

		return idsArr;
	}

	public String appendByComma(List<String> lists){
		StringBuffer sb = new StringBuffer();
		if (lists.isEmpty()){
			return "";
		}else{
			for (String s : lists){
				sb.append(",");
				sb.append(s);
			}
			return sb.substring(1).toString();
		}
	}

	/**
	 * 限制请求方式
	 * @param response
	 * @param header
	 * @param method
	 * @param type
	 * @return
	 */
	public Response methodPostFilter(Response response, ResponseHeader header, String method, String type) {
		if(method.equals(type)){
			response.setHeader(header);
			return response;
		}
		return renderFAIL("1001", response, header);
	}

	/**
	 * 返回对的Response
	 * @param data
	 * @param response
	 * @param header
	 * @return
	 */
	public Response renderSUC(Object data, Response response, ResponseHeader header) {
		header.setSuccflag(Response.SUCCESS);
		response.setHeader(header);
		response.setData(data);
		return response;
	}

	/**
	 * 返回错误的Response
	 * @param errorCode
	 * @param response
	 * @param header
	 * @return
	 */
	public Response renderFAIL(String errorCode, Response response, ResponseHeader header) {
		return renderFAIL(errorCode,null,response,header);
	}

	public Response renderFAIL(String errorCode, String errorMsg, Response response, ResponseHeader header) {
		header.setSuccflag(Response.FAIL);
		header.setErrorcode(errorCode);
		header.setErrormsg(errorMsg);
		response.setHeader(header);
		return response;
	}


	public UPPlatformRequest getUPRequest(String method, RequestHeader header){
		UPPlatformRequest request = new UPPlatformRequest();
		request.setApp_id(appId);
		request.setSign_type("RSA2");
		request.setCharset("UTF-8");
		request.setTimestamp(DateUtils.getDate("yyyyMMdd/HHmmss/"));
		request.setVersion("1.0");
		request.setMethod(method);
		request.setTrml_type("MOBILE_PHONE");
		request.setTrml_content(JSON.toJSONString(header.getPhone_info()));
		return request;
	}

	public static String sortParam(Map<String, String> params){

		return JSON.toJSONString(new TreeMap<String, String>(params));
	}

}
